package com.zk.ppa.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.zk.ppa.commom.exception.BaseException;
import com.zk.ppa.commom.exception.TokenTimeOutException;
import com.zk.ppa.dao.cache.CodeCache;
import com.zk.ppa.dao.po.Accout;
import com.zk.ppa.dao.repository.AccoutRepository;
import com.zk.ppa.service.AuthService;
import com.zk.ppa.service.dto.in.LoginDTO;
import com.zk.ppa.service.dto.out.ProfileOutDTO;
import com.zk.ppa.util.GraphicHelper;
import com.zk.ppa.util.MD5Util;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.OutputStream;
import java.util.UUID;

/**
 * @author chenxiaolong
 * @since 2021年03月21日 13:40:00
 */
@Service
@Slf4j
public class AuthServiceImpl implements AuthService {
    private static final String CODE_IMAGE_TYPE = "jpeg";
    private static final int CODE_IMAGE_WIDTH = 200;
    private static final int CODE_IMAGE_HEIGHT = 47;

    @Autowired
    private CodeCache codeCache;
    @Autowired
    private AccoutRepository accoutRepository;

    @Override
    public String createCode(String uuid, OutputStream outputStream){
        String code = GraphicHelper.create(CODE_IMAGE_WIDTH, CODE_IMAGE_HEIGHT, CODE_IMAGE_TYPE, outputStream);
        codeCache.addCode(uuid, code);
        return code;
    }

    @Override
    public String login(LoginDTO loginDTO) throws BaseException {
        log.info("登录服务参数{}", JSONObject.toJSON(loginDTO));
        String code = codeCache.getCode(loginDTO.getUuid());
        log.info("redis获得的code：{}", code);
        if(code == null || !code.equals(loginDTO.getCode())){
            throw new BaseException("验证码错误");
        }

        String md5Password = MD5Util.getMd5Password(loginDTO.getPassword());
        Accout accout = accoutRepository.getByAccount(loginDTO.getAccount());
        log.info("查询到的用户：{}", JSONObject.toJSON(accout));
        if(accout == null){
            throw new BaseException("账号不存在");
        }
        if(!md5Password.equals(accout.getPassword())) {
            throw new BaseException("密码错误");
        }

        String token = UUID.randomUUID().toString().replace("-", "");
        codeCache.addUserInfo(token, accout);

        return token;
    }

    @Override
    public ProfileOutDTO getProfile(String token) {
        Accout userInfo = codeCache.getUserInfo(token);
        if(userInfo == null){
            throw new TokenTimeOutException("登录过期");
        }

        ProfileOutDTO profileOutDTO = new ProfileOutDTO();
        profileOutDTO.setAccount(userInfo.getAccount())
                .setId(userInfo.getId())
                .setName(userInfo.getName())
                .setPassword(userInfo.getPassword())
                .setRole(userInfo.getRole())
                .setUnit(userInfo.getUnit());

        return profileOutDTO;
    }
}
